using IRepository;
using IServices;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using YL.Core.Dto;
using YL.Core.Entity;
using YL.Core.Entity.Meter;
using YL.Utils.Extensions;
using YL.Utils.Json;
using YL.Utils.Pub;
using YL.Utils.Table;

namespace Services
{
    public class Meter_InspectionServices : BaseServices<Inspection>, IMeter_InspectionServices
    {
        private readonly IMeter_InspectionRepository _repository;
        private readonly SqlSugarClient _client;

        public Meter_InspectionServices(SqlSugarClient client, IMeter_InspectionRepository repository) : base(repository)
        {
            _repository = repository;
            _client = client;
        }
        /// <summary>
        /// 各站点最近一次巡检情况
        /// </summary>
        /// <param name="bootstrap"></param>
        /// <returns></returns>
        public string PageList(Bootstrap.BootstrapParams bootstrap)
        {
            int totalNumber = 0;
            if (bootstrap.offset != 0)
            {
                bootstrap.offset = bootstrap.offset / bootstrap.limit + 1;
            }

            var query = _client.Queryable<AllLevelUserClientInfoView, DeviceInfo>
                ((s, u) => new object[] {
                   JoinType.Left,s.ClientId==u.ClientId
                 })
                .Where((s, u) => s.UserId== bootstrap.UserId && s.ClientId == u.ClientId)
                .Select((s, u) => new
                {
                    ClientId = s.ClientId.ToString(),
                    s.ClientName,
                    DeviceId = u.DeviceId.ToString(),
                    u.DeviceName
                }).MergeTable();

            if (!bootstrap.searchpara1.IsEmpty())
            {
                query.Where((s) => s.ClientName.Contains(bootstrap.searchpara1));
            }
            if (!bootstrap.searchpara2.IsEmpty())
            {
                query.Where((s) => s.DeviceName.Contains(bootstrap.searchpara2));
            }

            if (bootstrap.order.Equals("desc", StringComparison.OrdinalIgnoreCase))
            {
                query.OrderBy($"MergeTable.{bootstrap.sort} desc");
            }
            else
            {
                query.OrderBy($"MergeTable.{bootstrap.sort} asc");
            }
            var list = query.ToPageList(bootstrap.offset, bootstrap.limit, ref totalNumber);
            return Bootstrap.GridData(list, totalNumber).JilToJson();
        }
    }
}